package weeny.pre.face;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import weeny.face.LoadSaveBox;
import weeny.pre.util.Marker;
import weeny.util.logs.Debug;

public class MarkerLoadSaveBox extends LoadSaveBox{
	private List<Marker> markers = new ArrayList<Marker>();
	
	public MarkerLoadSaveBox(String dftFile, String title, Marker...markers){
		super(dftFile.endsWith(".zip") ? dftFile : dftFile+".zip", title);
		for (Marker marker : markers) {
			this.markers.add(marker);
		}
	}
	private Marker findMarker(String entryName){
		for(int i = 0; i<markers.size(); i++){
			if (markers.get(i).getGroup().equals(entryName)) {
				return markers.get(i);
			}
		}
		if (entryName.endsWith(".xml")) {
			entryName = entryName.substring(0, entryName.length()-4);
			return findMarker(entryName);
		}
		else {
			return null;
		}
	}
	private InputStream copyStream(InputStream is){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buff = new byte[2048];
		int size = -1;
		try {
			while ((size = is.read(buff, 0, buff.length)) != -1){
				baos.write(buff, 0, size);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ByteArrayInputStream(baos.toByteArray());
	}
	public void loadData(InputStream input) {
		ZipInputStream zis = null;
		if (input instanceof ZipInputStream) {
			zis = (ZipInputStream) input;
		}
		else {
			zis = new ZipInputStream(input);
		}
		List<Marker> tempList = new ArrayList<Marker>(markers);
		try {
			ZipEntry entry = null;
			while ((entry = zis.getNextEntry())!=null){
				Marker marker = findMarker(entry.getName());
				if (marker == null) {
					Debug.info("Ignore entry: "+entry);
				}
				else {
					marker.loadGraph(copyStream(zis));
					tempList.remove(marker);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!tempList.isEmpty()) {
			for (Marker marker : tempList) {
				Debug.prob("Cannot load: "+marker.getGroup());
			}
		}
	}

	public void saveData(OutputStream output) {
		ZipOutputStream zos = null;
		if (output instanceof ZipOutputStream) {
			zos = (ZipOutputStream) output;
		}
		else{
			zos = new ZipOutputStream(output);
		}
		try {
			for(Marker marker : markers){
				String name = marker.getGroup();
				name += name.endsWith(".xml")? "" : ".xml";
				zos.putNextEntry(new ZipEntry(name));
				marker.saveGraph(zos);
				zos.flush();
				zos.closeEntry();
			}
			zos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}